﻿using Newtonsoft.Json.Linq;

namespace VueShopApi.Common.Extensions
{
    public static class ObjectExtensions
    {
        /// <summary>
        /// 移除对象中的属性
        /// </summary>
        /// <param name="obj">待操作对象</param>
        /// <param name="attrs">待移除的属性列表</param>
        /// <returns></returns>
        public static object Omit(this object obj, params string[] attrs)
        {
            var o = JObject.FromObject(obj);
            foreach (var attr in attrs)
            {
                var j = o.SelectToken(attr);
                if (j != null)
                    o.Remove(attr);
            }
            return o;
        }

        /// <summary>
        /// 移除对象列表中的属性
        /// </summary>
        /// <param name="list">待操作对象列表</param>
        /// <param name="attrs">待移除的属性列表</param>
        /// <returns></returns>
        public static IEnumerable<object> Omit<T>(this IEnumerable<T> list, params string[] attrs) where T : class
        {
            var arr = JArray.FromObject(list);
            foreach (JObject obj in arr)
            {
                yield return obj.Omit(attrs);
            }
        }

        /// <summary>
        /// 选择对象中的属性
        /// </summary>
        /// <param name="obj">待操作对象</param>
        /// <param name="attrs">待移除的属性列表</param>
        /// <returns></returns>
        public static object Pick(this object obj, params string[] attrs)
        {
            var o2 = new JObject();

            var o = JObject.FromObject(obj);
            foreach (var attr in attrs)
            {
                var j = o.SelectToken(attr);
                if (j != null)
                    o2.Add(attr, j);
            }

            return o2;
        }

        /// <summary>
        /// 选择对象列表中的属性
        /// </summary>
        /// <param name="list">待操作对象列表</param>
        /// <param name="attrs">待移除的属性列表</param>
        /// <returns></returns>
        public static IEnumerable<object> Pick<T>(this IEnumerable<T> list, params string[] attrs) where T : class
        {
            var arr = JArray.FromObject(list);
            foreach (JObject obj in arr)
            {
                yield return obj.Pick(attrs);
            }
        }

        /// <summary>
        /// 合并其他对象到属性或对象
        /// </summary>
        /// <param name="obj1">合并对象</param>
        /// <param name="obj2">待合并对象</param>
        /// <param name="prop">属性</param>
        /// <returns></returns>
        public static object Merge(this object obj1, object obj2, string prop = "")
        {
            var o1 = JObject.FromObject(obj1);
            var o2 = JObject.FromObject(obj2);

            if (string.IsNullOrWhiteSpace(prop))
            {
                o1.Merge(o2);
            }
            else
            {
                o1.Add(prop, o2);
            }
            return o1;
        }
    }
}
